import { GameDataModel } from "./GameDataModel";
import { GameEvent } from "./GameEvent";
import { PlayerController } from "./PlayerController";
import { StarController } from "./StarController";
import { UIController } from "./UIController";
const {ccclass, property} = cc._decorator;

@ccclass
export class GameManager extends cc.Component implements GameCtrler {
    private playerCtrler: PlayerController;
    private starCtrler: StarController;
    private uiCtrler: UIController;

    @property
    private starAliveTime: number = 0;

    @property
    private createStarInterval: number = 0;

    @property
    private createStarAreaLimit: cc.Vec4 = new cc.Vec4(0, 0, 0, 0);

    @property
    private starDetectRadius: number = 0;

    @property
    private playerJumpDuration: number = 0;

    @property
    private playerJumpHeight: number = 0;

    @property
    private playerMoveAreaLimit: cc.Vec2 = cc.Vec2.ZERO;

    @property
    private playerInitPos: cc.Vec3 = cc.Vec3.ZERO;

    protected onLoad(): void {
        let playerCtrlerNode: cc.Node = cc.find('game/player');
        this.playerCtrler = new PlayerController(playerCtrlerNode, this.playerJumpDuration, this.playerJumpHeight, this.playerInitPos, this.playerMoveAreaLimit);

        this.starCtrler = new StarController(this.starAliveTime, this.createStarInterval, this.createStarAreaLimit, this.starDetectRadius, this.playerCtrler);

        this.uiCtrler = new UIController();

        GameEvent.OnStartGame = this.startGame.bind(this);
        GameEvent.OnReplayGame = this.restartGame.bind(this);
        GameEvent.OnFinishGame = this.finishGame.bind(this);
    }

    protected start(): void {
        this.prepareGame();
    }

    protected onDestroy(): void {
        GameEvent.OnStartGame = null;
        GameEvent.OnReplayGame = null;
        GameEvent.OnFinishGame = null;
    }

    public prepareGame(): void {
        this.playerCtrler.prepareGame();
        this.starCtrler.prepareGame();
        this.uiCtrler.prepareGame();
    }

    public startGame(): void{
        console.log('开始游戏');
        GameDataModel.getInstance().clearScore();
        this.playerCtrler.startGame();
        this.starCtrler.startGame();
        this.uiCtrler.startGame();
    }

    public finishGame(): void{
        console.log('游戏结束');
        this.playerCtrler.finishGame();
        this.starCtrler.finishGame();
        this.uiCtrler.finishGame();
        GameDataModel.getInstance().saveScore();
    }
    
    public restartGame(): void{
        console.log('重新开始');
        GameDataModel.getInstance().clearScore();
        this.playerCtrler.restartGame();
        this.starCtrler.restartGame();
        this.uiCtrler.restartGame();
    }
}
